package com.example.terminal.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.ColorInt;
import androidx.annotation.Nullable;

import com.example.terminal.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.ColorInt;
import androidx.annotation.Nullable;

public class CustomProgress extends View {
    // 默认属性值
    private static final int DEFAULT_MAX_VALUE = 100;
    private static final int DEFAULT_CURRENT_VALUE = 0;
    private static final int DEFAULT_PROGRESS_COLOR = 0xFF3F51B5;
    private static final int DEFAULT_BACKGROUND_COLOR = 0xFFE0E0E0;
    private static final int DEFAULT_STROKE_WIDTH = 10;
    private static final float DEFAULT_START_ANGLE = -90; // 从顶部开始
    private static final float DEFAULT_SWEEP_ANGLE = 360; // 完整圆形
    private static final float DEFAULT_TEXT_SIZE = 40; // 文字大小
    private static final int DEFAULT_NORMAL_TEXT_COLOR = 0xFF333333; // 正常文字颜色
    private static final int DEFAULT_WARNING_TEXT_COLOR = 0xFFFF0000; // 警告文字颜色
    private static final int DEFAULT_WARNING_PROGRESS_COLOR = 0xFFFF0000; // 警告进度条颜色

    // 进度条属性
    private int maxValue;          // 总长度（最大值）
    private int currentValue;      // 当前进度值
    private int progressColor;     // 进度条颜色
    private int backgroundColor;   // 背景圆环颜色
    private int strokeWidth;       // 线条宽度
    private float startAngle;      // 起始角度
    private float maxSweepAngle;   // 最大扫描角度（总角度）

    // 文本属性（新增）
    private float textSize;        // 百分比文字大小
    private int normalTextColor;   // 正常状态文字颜色
    private int warningTextColor;  // 警告状态文字颜色
    private int warningProgressColor; // 警告状态进度条颜色

    // 画笔
    private Paint progressPaint;
    private Paint backgroundPaint;
    private Paint textPaint;       // 文字画笔（新增）

    // 绘制区域
    private RectF rectF;

    public CustomProgress(Context context) {
        this(context, null);
    }

    public CustomProgress(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomProgress(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttrs(context, attrs);
        initPaints();
    }

    /**
     * 初始化自定义属性
     */
    private void initAttrs(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomProgress);

        // 原有属性
        maxValue = typedArray.getInt(R.styleable.CustomProgress_maxValue, DEFAULT_MAX_VALUE);
        currentValue = typedArray.getInt(R.styleable.CustomProgress_currentValue, DEFAULT_CURRENT_VALUE);
        progressColor = typedArray.getColor(R.styleable.CustomProgress_progressColor, DEFAULT_PROGRESS_COLOR);
        backgroundColor = typedArray.getColor(R.styleable.CustomProgress_backgroundColor, DEFAULT_BACKGROUND_COLOR);
        strokeWidth = typedArray.getDimensionPixelSize(R.styleable.CustomProgress_strokeWidth, DEFAULT_STROKE_WIDTH);
        startAngle = typedArray.getFloat(R.styleable.CustomProgress_startAngle, DEFAULT_START_ANGLE);
        maxSweepAngle = typedArray.getFloat(R.styleable.CustomProgress_maxSweepAngle, DEFAULT_SWEEP_ANGLE);

        // 新增文本属性
        textSize = typedArray.getDimension(R.styleable.CustomProgress_textSize, DEFAULT_TEXT_SIZE);
        normalTextColor = typedArray.getColor(R.styleable.CustomProgress_normalTextColor, DEFAULT_NORMAL_TEXT_COLOR);
        warningTextColor = typedArray.getColor(R.styleable.CustomProgress_warningTextColor, DEFAULT_WARNING_TEXT_COLOR);
        warningProgressColor = typedArray.getColor(R.styleable.CustomProgress_warningProgressColor, DEFAULT_WARNING_PROGRESS_COLOR);

        typedArray.recycle();

        // 确保当前值在有效范围内
        currentValue = Math.max(0, currentValue);
    }

    /**
     * 初始化画笔
     */
    private void initPaints() {
        // 背景画笔
        backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        backgroundPaint.setColor(backgroundColor);
        backgroundPaint.setStyle(Paint.Style.STROKE);
        backgroundPaint.setStrokeWidth(strokeWidth);
        backgroundPaint.setStrokeCap(Paint.Cap.ROUND);

        // 进度画笔
        progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        progressPaint.setStyle(Paint.Style.STROKE);
        progressPaint.setStrokeWidth(strokeWidth);
        progressPaint.setStrokeCap(Paint.Cap.ROUND);

        // 文字画笔（新增）
        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setTextSize(textSize);
        textPaint.setTextAlign(Paint.Align.CENTER); // 文字水平居中

        rectF = new RectF();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 确保是正方形
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        int size = Math.min(width, height);
        setMeasuredDimension(size, size);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 计算绘制区域（考虑线条宽度）
        int padding = strokeWidth / 2;
        rectF.set(padding, padding, getWidth() - padding, getHeight() - padding);

        // 绘制背景圆环
        canvas.drawArc(rectF, startAngle, maxSweepAngle, false, backgroundPaint);

        // 计算当前进度比例
        float progressRatio = maxValue == 0 ? 0 : (float) currentValue / maxValue;
        float currentSweepAngle = progressRatio * maxSweepAngle;

        // 判断是否超限（新增核心逻辑）
        boolean isOverMax = currentValue > maxValue;

        // 设置进度条颜色（根据是否超限切换）
        progressPaint.setColor(isOverMax ? warningProgressColor : progressColor);

        // 绘制进度圆环
        canvas.drawArc(rectF, startAngle, currentSweepAngle, false, progressPaint);

        // 绘制中间百分比文字（新增核心逻辑）
        drawPercentageText(canvas, progressRatio, isOverMax);
    }

    /**
     * 绘制中间的百分比文字
     */
    private void drawPercentageText(Canvas canvas, float progressRatio, boolean isOverMax) {
        // 计算百分比（取整数）
        int percentage = (int) (progressRatio * 100);
        String text = percentage + "%";

        // 设置文字颜色（根据是否超限切换）
        textPaint.setColor(isOverMax ? warningTextColor : normalTextColor);

        // 计算文字垂直居中位置（解决文字基线问题）
        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
        float baseLineY = getHeight() / 2f - (fontMetrics.top + fontMetrics.bottom) / 2f;

        // 绘制文字
        canvas.drawText(text, getWidth() / 2f, baseLineY, textPaint);
    }

    /**
     * 设置最大值（总长度）
     */
    public void setMaxValue(int maxValue) {
        if (maxValue <= 0) {
            throw new IllegalArgumentException("最大值必须大于0");
        }
        this.maxValue = maxValue;
        invalidate();
    }

    /**
     * 获取最大值
     */
    public int getMaxValue() {
        return maxValue;
    }

    /**
     * 设置当前进度值（取消原有限制，允许超过最大值）
     */
    public void setCurrentValue(int currentValue) {
        this.currentValue = Math.max(0, currentValue); // 只限制最小值，允许超过最大值
        invalidate(); // 重绘
    }

    /**
     * 获取当前进度值
     */
    public int getCurrentValue() {
        return currentValue;
    }

    /**
     * 设置进度条颜色
     */
    public void setProgressColor(@ColorInt int color) {
        this.progressColor = color;
        invalidate();
    }

    /**
     * 设置背景圆环颜色
     */
    @Override
    public void setBackgroundColor(@ColorInt int color) {
        this.backgroundColor = color;
        backgroundPaint.setColor(color);
        invalidate();
    }

    /**
     * 设置线条宽度
     */
    public void setStrokeWidth(int width) {
        this.strokeWidth = width;
        progressPaint.setStrokeWidth(width);
        backgroundPaint.setStrokeWidth(width);
        invalidate();
    }

    // 新增文本相关设置方法
    public void setTextSize(float textSize) {
        this.textSize = textSize;
        textPaint.setTextSize(textSize);
        invalidate();
    }

    public void setNormalTextColor(@ColorInt int color) {
        this.normalTextColor = color;
        invalidate();
    }

    public void setWarningTextColor(@ColorInt int color) {
        this.warningTextColor = color;
        invalidate();
    }

    public void setWarningProgressColor(@ColorInt int color) {
        this.warningProgressColor = color;
        invalidate();
    }
}

